<template>
  <view class="uni-map-container" v-if="showMap">
    <web-view 
      :src="mapUrl" 
      @message="handleMessage"
      class="map-webview"
    ></web-view>
  </view>
</template>
<script>
import { getAddressCode } from "@/api/address";
import config from '@/config/config'
export default {
  data() {
    return {
      config,
      showMap: false,
      mapUrl: ''
    };
  },
  mounted() {
    this.init();
  },
  
  props: {
    // 是否显示地图
    visible: {
      type: Boolean,
      default: false
    }
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        this.showGoogleMap();
      } else {
        this.showMap = false;
      }
    }
  },
  methods: {
    // 显示谷歌地图选择器
    showGoogleMap() {
      const apiKey = this.config.googleMapsApiKey || 'YOUR_GOOGLE_MAPS_API_KEY';
      // 构建地图页面URL，传递API密钥
      this.mapUrl = `/hybrid/html/google-map-picker.html?apiKey=${encodeURIComponent(apiKey)}`;
      this.showMap = true;
    },
    
    // 处理web-view消息
    handleMessage(event) {
      const message = event.detail.data[0];
      if (message.type === 'locationSelected') {
        this.handleLocationSelected(message.data);
      } else if (message.type === 'mapClosed') {
        this.closeMap();
      }
    },
    
    // 处理位置选择
    handleLocationSelected(locationData) {
      const { latitude, longitude, address, name } = locationData;
      
      // 获取地址详情
      this.posToCity(latitude, longitude).then((val) => {
        // 获取地址code
        getAddressCode(
          val.regeocode.addressComponent.citycode || '',
          val.regeocode.addressComponent.township || val.regeocode.addressComponent.district
        ).then((code) => {
          const result = {
            ...val,
            latitude,
            longitude,
            address,
            name,
            ...code
          };
          this.$emit("callback", result);
          this.closeMap();
        }).catch((err) => {
          console.warn('获取地址code失败:', err);
          // 即使获取code失败，也返回基本信息
          const result = {
            ...val,
            latitude,
            longitude,
            address,
            name
          };
          this.$emit("callback", result);
          this.closeMap();
        });
      }).catch((err) => {
        console.warn('地理编码失败:', err);
        // 如果地理编码失败，返回基本位置信息
        const result = {
          latitude,
          longitude,
          address,
          name,
          regeocode: {
            formatted_address: address,
            addressComponent: {
              city: '',
              district: '',
              province: '',
              township: '',
              citycode: ''
            }
          }
        };
        this.$emit("callback", result);
        this.closeMap();
      });
    },
    
    // 关闭地图
    closeMap() {
      this.showMap = false;
      this.$emit("close");
    },
    
    // 初始化地图并且调用（兼容原有调用方式）
    initMap() {
      this.showGoogleMap();
    },

    // 根据当前客户端判断展示不同类型数据
    init() {
      // 统一使用谷歌地图，不再区分平台
      if (this.visible) {
        this.showGoogleMap();
      }
    },

    // 检查位置权限（可选）
    checkLocationPermission() {
      // 在使用谷歌地图时，位置权限由浏览器处理
      // 这里可以添加额外的权限检查逻辑
      return true;
    },
    // 获取城市的数据 - 使用谷歌地图地理编码API
    posToCity(latitude, longitude) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `https://maps.googleapis.com/maps/api/geocode/json`,
          method: "GET",
          data: {
            key: config.googleMapsApiKey, // 谷歌地图API密钥
            latlng: `${latitude},${longitude}`,
            language: 'zh-CN' // 设置返回中文结果
          },
          success: ({ data }) => {
            const { status, results } = data;
            if (status === "OK" && results.length > 0) {
              // 转换谷歌地图返回格式为兼容原有格式
              const result = results[0];
              const addressComponents = result.address_components;
              
              // 提取地址组件
              let city = '', district = '', province = '';
              addressComponents.forEach(component => {
                if (component.types.includes('locality')) {
                  city = component.long_name;
                }
                if (component.types.includes('sublocality') || component.types.includes('administrative_area_level_3')) {
                  district = component.long_name;
                }
                if (component.types.includes('administrative_area_level_1')) {
                  province = component.long_name;
                }
              });
              
              // 构造兼容原有格式的返回数据
              const compatibleData = {
                status: "1",
                regeocode: {
                  formatted_address: result.formatted_address,
                  addressComponent: {
                    city: city,
                    district: district,
                    province: province,
                    township: district,
                    citycode: '', // 谷歌地图不直接提供citycode，可能需要额外处理
                  }
                }
              };
              resolve(compatibleData);
            } else {
              reject(data.error_message || '地理编码失败');
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.uni-map-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: #fff;
}

.map-webview {
  width: 100%;
  height: 100%;
}
</style>